/*
 * TimerTest.c
 *
 *  Created on: Nov 25, 2011
 *      Author: shaohong
 */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>

static int timerInterval = 20; // 20 milliseconds
static int timerTriggerCounter = 0;
static int timerFrequency = 1000 / timerInterval;


static void myhandler(int sigType) {
   int errsave;
   errsave = errno;
   timerTriggerCounter ++;
   if (timerTriggerCounter == timerFrequency ){
	   time_t tcurrent = time(NULL);
	   fprintf(stderr, "The current time is: %s\n", ctime(&tcurrent));
//	   write(STDERR_FILENO, &aster, 1);
	   errno = errsave;
	   // reset timerTriggerCounter
	   timerTriggerCounter = 0;
   }


}

static int setupinterrupt(void) {          /* set up myhandler for SIGALRM */
   struct sigaction act;
   act.sa_handler = myhandler;
   act.sa_flags = 0;
   return (sigemptyset(&act.sa_mask) || sigaction(SIGALRM, &act, NULL));
}

static int startTimer(unsigned int timerInterval) {    /* set ITIMER_PROF for 2-second intervals */
   struct itimerval value;
   value.it_interval.tv_sec = timerInterval / 1000;
   value.it_interval.tv_usec = (timerInterval % 1000) * 1000;
   value.it_value = value.it_interval;
   return (setitimer(ITIMER_REAL, &value, NULL));
}

int main(void) {
   if (setupinterrupt()) {
      perror("Failed to set up handler for SIGPROF");
      return 1;
   }
   if (startTimer(timerInterval) == -1) {
      perror("Failed to set up the ITIMER_REAL interval timer");
      return 1;
   }
   for ( ; ; );
   /* execute rest of main program here */
}

